package top.blueShark.template.satoken;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import cn.dev33.satoken.exception.DisableServiceException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalException {

	/**
	 * 全局异常拦截（拦截项目中的所有异常）
	 * @param e 异常对象
	 * @param request 请求对象
	 * @param response 响应对象
	 * @return 统一封装的响应体，带合适的 HTTP 状态码
	 */
	@ExceptionHandler
	public ResponseEntity<AjaxJson> handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) {
		System.out.println("全局异常---------------");
		e.printStackTrace();

		AjaxJson aj;
		HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; // 默认500

		if (e instanceof NotLoginException) { // 未登录异常，返回401
			NotLoginException ee = (NotLoginException) e;
			aj = AjaxJson.getError("未登录，请登录后再次访问", ee.getMessage());
			status = HttpStatus.UNAUTHORIZED; // 401
		}
		else if(e instanceof NotRoleException) { // 角色异常
			NotRoleException ee = (NotRoleException) e;
			aj = AjaxJson.getError("无此角色：" + ee.getRole(), null);
			status = HttpStatus.FORBIDDEN; // 403
		}
		else if(e instanceof NotPermissionException) { // 权限异常
			NotPermissionException ee = (NotPermissionException) e;
			aj = AjaxJson.getError("无此权限：" + ee.getPermission(), null);
			status = HttpStatus.FORBIDDEN; // 403
		}
		else if(e instanceof DisableServiceException) { // 被封禁异常
			DisableServiceException ee = (DisableServiceException) e;
			aj = AjaxJson.getError("当前账号 " + ee.getService() + " 服务已被封禁 (level=" + ee.getLevel() + ")：" + ee.getDisableTime() + "秒后解封", null);
			status = HttpStatus.FORBIDDEN; // 403
		}
		else { // 其他异常，返回500
			aj = AjaxJson.getError(e.getMessage());
			status = HttpStatus.INTERNAL_SERVER_ERROR;
		}

		return new ResponseEntity<>(aj, status);
	}
}
